package com.testing.xml_pull;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ArrayList<Student> list;
    private Student stu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();

            XmlPullParser parser = factory.newPullParser();

            parser.setInput(getAssets().open("NewFile.xml"), "utf-8");

            int type = parser.getEventType();

            while (type != XmlPullParser.END_DOCUMENT) {
                switch (type) {
                    case XmlPullParser.START_DOCUMENT:
                        list = new ArrayList<>();
                        break;
                    case XmlPullParser.START_TAG:
                        String tagName = parser.getName();
                        if ("student".equals(tagName)) {
                            stu = new Student();
                        }
                        if ("name".equals(tagName)) {
                            String name = parser.nextText();
                            stu.name = name;
                        }
                        if ("age".equals(tagName)) {
                            String age = parser.nextText();
                            stu.age = age;
                        }
                        if ("sex".equals(tagName)) {
                            String sex = parser.nextText();
                            stu.sex = sex;
                        }
                        break;
                    case XmlPullParser.END_TAG:

                        if ("student".equals(parser.getName())) {
                            list.add(stu);
                            stu = null;
                        }
                        break;
                }

                //下移
                type = parser.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        Log.d("zzz", list.toString());
    }
}
